//
//  SCAnimation.m
//  DoulinClient
//
//  Created by YLKJ on 2019/2/26.
//

#import "SCAnimation.h"

@interface SCAnimation ()<CAAnimationDelegate>
@property (nonatomic, strong) NSMutableArray * layerAry;
@end

@implementation SCAnimation
SingletonM(SCAnimation)

- (void)animationFromPoint:(CGPoint)startP toPoint:(CGPoint)toP key:(NSString *)key type:(SCAnimationType)type {
    if (key == nil) {
        return;
    }
    NSLog(@"<-- %s, %d --> %@ - %@", __FUNCTION__, __LINE__, NSStringFromCGPoint(startP), NSStringFromCGPoint(toP));
    UIWindow * keyW = [UIApplication sharedApplication].keyWindow;
    CALayer *layer = [CALayer layer];
    layer.frame = CGRectMake(0, 0, 10, 10);
    layer.position = startP;
    layer.backgroundColor = [UIColor redColor].CGColor;
    layer.cornerRadius = layer.frame.size.width * 0.5;
    layer.masksToBounds = YES;
    [keyW.layer addSublayer:layer];
    //创建关键帧
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.delegate = self;
    //动画时间
    animation.duration = 0.50;
    //当动画完成，停留到结束位置
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    //当方法名字遇到create,new,copy,retain，都需要管理内存
    CGMutablePathRef path = CGPathCreateMutable();
    //设置起点
    CGPathMoveToPoint(path, NULL, startP.x, startP.y);
    if (type == SCAnimationTypeDrop) {
        //控点
        CGPoint ctrlP = CGPointMake(toP.x, startP.y);
        CGPathAddQuadCurveToPoint(path, NULL, ctrlP.x, ctrlP.y, toP.x, toP.y);
    } else {
        //控点
        CGPoint ctrlP = startP;
        CGPathAddQuadCurveToPoint(path, NULL, ctrlP.x, ctrlP.y, toP.x, toP.y);
    }
    //设置动画路径
    animation.path = path;
    //执行动画
    [layer addAnimation:animation forKey:key];
    [self.layerAry addObject:key];
    //释放路径
    CGPathRelease(path);
}
- (void)animationDidStart:(CAAnimation *)anim {
    NSLog(@"<-- %s, %d --> 动画开始了", __FUNCTION__, __LINE__);
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    UIWindow * keyW = [UIApplication sharedApplication].keyWindow;
    NSLog(@"<-- %s, %d --> 动画完成了", __FUNCTION__, __LINE__);
    @synchronized (self) {
        for (CALayer * layer in keyW.layer.sublayers) {
            for (NSString * key in self.layerAry) {
                if ([[layer animationForKey:key] isEqual:anim]) {
                    [layer removeFromSuperlayer];
                    return;
                }
            }
        }
    }
}
- (NSMutableArray *)layerAry {
    if (!_layerAry) {
        self.layerAry = [@[] mutableCopy];
    }
    return _layerAry;
}

@end
